package com.work.work.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.work.work.dto.LoginResponse;
import com.work.work.dto.UserDTO;
import com.work.work.entity.*;
import com.work.work.mapper.RoleMapper;
import com.work.work.mapper.UserMapper;
import com.work.work.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RoleService roleService;
    @Autowired
    private TeamService teamService;
    @Autowired
    private NotificationService notificationService;

    @Autowired
    private TaskService taskService;
    @Override
    public LoginResponse loginWithRole(String username, String password) {
        // 查询用户
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username)
                .eq(User::getPassword, password);
        User user = getOne(wrapper);

        if (user == null) {
            return null;
        }

        // 获取角色信息
        Role role = roleMapper.selectById(user.getRoleId());

        // 转换为 DTO
        LoginResponse response = new LoginResponse();
        BeanUtils.copyProperties(user, response);
        response.setRoleId(user.getRoleId());

        if (role != null) {
            response.setRolename(role.getRolename());
        }

        return response;
    }


    @Override
    public Page<UserDTO> getUsersWithDetail(Page<User> page) {
        // 查询用户基本信息
        Page<User> userPage = this.page(page);

        // 创建结果页
        Page<UserDTO> resultPage = new Page<>();
        resultPage.setTotal(userPage.getTotal());
        resultPage.setCurrent(userPage.getCurrent());
        resultPage.setSize(userPage.getSize());

        // 转换并填充额外信息
        List<UserDTO> records = userPage.getRecords().stream()
                .map(user -> {
                    UserDTO dto = new UserDTO();
                    BeanUtils.copyProperties(user, dto);

                    // 获取角色名称
                    Role role = roleService.getById(user.getRoleId());
                    if (role != null) {
                        dto.setRolename(role.getRolename());
                    }

                    // 获取团队名称
                    if (user.getTeamId() != null) {
                        Team team = teamService.getById(user.getTeamId());
                        if (team != null) {
                            dto.setTeamname(team.getTeamname());
                        }
                    }

                    return dto;
                })
                .collect(Collectors.toList());

        resultPage.setRecords(records);
        return resultPage;
    }
    @Override
    @Transactional
    public boolean deleteUserAndRelatedData(Integer userId) {
        // 1. 验证用户是否存在
        User user = this.getById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        try {
            // 2. 删除该用户相关的通知记录
            notificationService.remove(new LambdaQueryWrapper<Notification>()
                    .eq(Notification::getSenderId, userId)
                    .or()
                    .eq(Notification::getReceiverId, userId));

            // 3. 更新任务表中的assignee为null
            taskService.update(new UpdateWrapper<Task>()
                    .set("assignee", null)
                    .eq("assignee", user.getUsername()));

            // 4. 删除用户
            return this.removeById(userId);
        } catch (Exception e) {
            throw new RuntimeException("删除用户失败: " + e.getMessage());
        }
    }
    @Override
    @Transactional
    public boolean batchUpdateUserTeam(Integer teamId, List<Integer> userIds) {
        if (teamId != null) {
            // 检查团队是否存在
            Team team = teamService.getById(teamId);
            if (team == null) {
                throw new RuntimeException("团队不存在");
            }
        }

        // 批量更新用户的团队ID
        return update(new UpdateWrapper<User>()
                .in("id", userIds)
                .set("team_id", teamId));
    }
}